package com.xbjtech.vipsystem.service;

import com.xbjtech.vipsystem.dto.Menu;
import com.xbjtech.vipsystem.mapper.UserMapper;
import com.xbjtech.vipsystem.po.User;
import com.xbjtech.vipsystem.vo.UserOptVO;
import org.apache.ibatis.session.ExecutorType;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author leejun.happy@gmail.com
 * @created 2019-07-19
 */
@Service
public class UserService extends BaseService<User> {

    @Autowired
    UserMapper userMapper;

    @Autowired
    SqlSessionFactory sqlSessionFactory;

    public void insertRoleRelation(UserOptVO vo) {
        // 第一种： insert into t_user values(?,?),(?,?),(?,?),(?,?) 一般不这么干
        // 第二种： 遍历 insert  如果数据量比较大的时候，这个效率不好
        // 第三种： ExecutorType.BATCH
        // sql plus  cvs文件 => oracle  不需要写java代码

        SqlSession sqlSession = 
                sqlSessionFactory.openSession(ExecutorType.BATCH, false);
        UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
        try {
            if (null != vo && null != vo.getRoleIds()) {
                userMapper.deleteRoleRelationByUserId(vo.getUserId());
                if (null != vo.getRoleIds() && vo.getRoleIds().size() > 0) {
                    for (Integer roleId : vo.getRoleIds()) {
                        userMapper.insertRoleRelation(vo.getUserId(), roleId);
                    }
                }
            }
            sqlSession.commit();
        } catch (Exception e) {
            sqlSession.rollback();
            throw e; // 注意一下，这个异常一定要抛出来
        } finally {
            sqlSession.close();
        }

    }

    public List<Menu> selectMenus(String username) {
        return userMapper.selectMenus(username);
    }

}
